Navigation
(Method-1) React Navigation(react-navigation)
-
We will create 2 screens (home, profile) and navigate between them
$ npm install @react-navigation/native @react-navigation/native-stack
// Install for expo managed project
$ npx expo install react-native-screens react-native-safe-area-context
Creating 2 screens and navigating between them
|
1. import createNativeStackNavigator 2. Whole app need to wrapped inside createNativeStackNavigator().Navigator in App.js 3. Stack.Screen defines 2 screens: name="Home" name="Profile" 4. We can set options such as the screen title for each screen in the options prop of Stack.Screen. options={{title: 'Welcome Screen'}} options={{title: 'Profile Screen'}} 5. Each screen takes navigation prop. This prop has various methods to link to other screen navigation.navigate to go to profile screen. |
Expo Router
-
Navigate from Home Screen to ProfileScreen and Back from profile screen to home screen
///////// _layout.tsx /////////////
import { Stack } from "expo-router";
// Defines the navigation stack (Required) in expo-router
// We can provide different screen options here
export default function RootLayout() {
return (
<Stack>
<Stack.Screen name="index" options={{ headerShown: false, title: 'Home' }} />
<Stack.Screen name="ProfileScreen" options={{ title: 'ProfileScreen' }} />
</Stack>
);
}
///////// index.tsx /////////
import { View, Text, Button } from 'react-native';
import { useRouter } from 'expo-router';
export default function HomeScreen() {
const router = useRouter();
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Welcome to Home Screen</Text>
<Button
title="Go to Profile (Router)"
onPress={() => router.push({ pathname: "/ProfileScreen" })}
/>
</View>
);
}
///////// ProfileScreen.tsx /////////
import { View, Text, Button } from 'react-native';
import { useLocalSearchParams, useRouter } from 'expo-router';
export default function ProfileScreen() {
const router = useRouter();
const { name } = useLocalSearchParams();
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>This is the Profile Screen</Text>
{/* Go back to Home Screen */}
<Button title="Go Back" onPress={() => router.back()} />
</View>
);
}